package cn.yuanqiao.archive.bianyan.service.Impl;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.bianyan.domain.YqZhuantiChengguo;
import cn.yuanqiao.archive.bianyan.domain.YqZtcgFile;
import cn.yuanqiao.archive.bianyan.mapper.YqZhuantiChengguoMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZtcgFileMapper;
import cn.yuanqiao.archive.bianyan.service.IYqZhuantiChengguoService;
import cn.yuanqiao.archive.bianyan.utils.PictureUploadUtils;
import cn.yuanqiao.archive.bianyan.utils.ZipUtils;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 专题成果Service业务层处理
 *
 * @ProjectName: ruoyi-modules-system
 * @Package: cn.yuanqiao.archive.bianyan.service.Impl
 * @ClassName: YqZhuantiChengguoServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2023/7/11 11:06
 * @Version: 1.0
 */
@Service
public class YqZhuantiChengguoServiceImpl implements IYqZhuantiChengguoService {
    @Autowired
    private YqZhuantiChengguoMapper yqZhuantiChengguoMapper;

    @Autowired
    private YqZtcgFileMapper ztcgFileMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    /**
     * 查询专题成果
     *
     * @param chengguoId 专题成果主键
     * @return 专题成果
     */
    @Override
    public YqZhuantiChengguo selectYqZhuantiChengguoByChengguoId(String chengguoId) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        YqZhuantiChengguo yqZhuantiChengguo = yqZhuantiChengguoMapper.selectYqZhuantiChengguoByChengguoId(chengguoId, cgTbale);

        yqZhuantiChengguo.setZtcgFiles(selectztcgFileChengguoId(chengguoId));
        return yqZhuantiChengguo;
    }

    /**
     * 查询附件列表
     *
     * @param chengguoId
     * @return
     */
    @Override
    public List<YqZtcgFile> selectztcgFileChengguoId(String chengguoId) {
        String tableCode = SecurityUtils.getTenantCode();
        String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
        List<YqZtcgFile> yqZtcgFiles = ztcgFileMapper.selectYqZtcgFileByCgId(chengguoId, fileTable);
        return yqZtcgFiles;
    }

    /**
     * 查询专题成果列表
     *
     * @param yqZhuantiChengguo 专题成果
     * @return 专题成果
     */
    @Override
    public List<YqZhuantiChengguo> selectYqZhuantiChengguoList(YqZhuantiChengguo yqZhuantiChengguo) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        yqZhuantiChengguo.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        return yqZhuantiChengguoMapper.selectYqZhuantiChengguoList(yqZhuantiChengguo, cgTbale);
    }

    /**
     * 新增专题成果
     *
     * @param yqZhuantiChengguo 专题成果
     * @return 结果
     */
    @Override
    @Transactional
    public int insertYqZhuantiChengguo(YqZhuantiChengguo yqZhuantiChengguo) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
        yqZhuantiChengguo.setCreateTime(DateUtils.getNowDate());
        String chengguoId = String.valueOf(SnowflakeIdGenerator.generateId());
        yqZhuantiChengguo.setChengguoId(chengguoId);
        yqZhuantiChengguo.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        yqZhuantiChengguo.setCREATOR(SecurityUtils.getUsername());
        //先插入文件
        if (yqZhuantiChengguo.getZtcgFiles() != null && yqZhuantiChengguo.getZtcgFiles().size() > 0) {
            yqZhuantiChengguo.getZtcgFiles().stream().forEach(f -> {
                f.setChengguoId(chengguoId);
                ztcgFileMapper.updateBzYqZtcgFile(f, fileTable);
            });

        }
        return yqZhuantiChengguoMapper.insertYqZhuantiChengguo(yqZhuantiChengguo, cgTbale);
    }

    /**
     * 修改专题成果
     *
     * @param yqZhuantiChengguo 专题成果
     * @return 结果
     */
    @Override
    @Transactional
    public int updateYqZhuantiChengguo(YqZhuantiChengguo yqZhuantiChengguo) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        YqZhuantiChengguo yqZhuantiChengguos = yqZhuantiChengguoMapper.selectYqZhuantiChengguoByChengguoId(yqZhuantiChengguo.getChengguoId(), cgTbale);
        String userId=String.valueOf(SecurityUtils.getUserId());
        if (!userId.equals(yqZhuantiChengguos.getCreatorId())){
            throw new ServiceException("不允许修改他人数据,请重新选择!");
        }
        return yqZhuantiChengguoMapper.updateYqZhuantiChengguo(yqZhuantiChengguo, cgTbale);
    }

    /**
     * 批量删除专题成果
     *
     * @param chengguoIds 需要删除的专题成果主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteYqZhuantiChengguoByChengguoIds(String[] chengguoIds) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
        List<YqZhuantiChengguo> yqZhuantiChengguos = yqZhuantiChengguoMapper.selectYqZhuantiChengguoByChengguoIdS(chengguoIds, cgTbale);
        String userId=String.valueOf(SecurityUtils.getUserId());
        boolean allMatch = yqZhuantiChengguos.stream().allMatch(a -> userId.equals(a.getCreatorId()));
        if (!allMatch) {
            throw new ServiceException("您选择的数据包含其他人的数据,请重新选择!");
        }
        ztcgFileMapper.deleteYqZtcgFileByFileIds(chengguoIds, fileTable);
        return yqZhuantiChengguoMapper.deleteYqZhuantiChengguoByChengguoIds(chengguoIds, cgTbale);
    }

    /**
     * 删除专题成果信息
     *
     * @param chengguoId 专题成果主键
     * @return 结果
     */
    @Override
    public int deleteYqZhuantiChengguoByChengguoId(String chengguoId) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
        ztcgFileMapper.deleteYqZtcgFileByCgId(chengguoId, fileTable);
        YqZhuantiChengguo yqZhuantiChengguos = yqZhuantiChengguoMapper.selectYqZhuantiChengguoByChengguoId(chengguoId, cgTbale);
        String userId=String.valueOf(SecurityUtils.getUserId());
        if (!userId.equals(yqZhuantiChengguos.getCreatorId())) {
            throw new ServiceException("不允许删除他人数据,请重新选择!");
        }
        return yqZhuantiChengguoMapper.deleteYqZhuantiChengguoByChengguoId(chengguoId, cgTbale);
    }

    @Override
    public void download(String chengguoId, HttpServletResponse response) throws Exception {
        String tableCode = SecurityUtils.getTenantCode();
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        if (ObjectUtils.isNotEmpty(chengguoId)) {
            String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
            String[] id = chengguoId.split(",");
            List<YqZtcgFile> yqZtcgFiles = ztcgFileMapper.selectYqZtcgFileDownl(id, fileTable);
            if (yqZtcgFiles == null && yqZtcgFiles.size() == 0) {
                throw new ServiceException("请先上传附件后,再进行下载!");
            }
            String zipName = "CG_";
            ZipUtils zipUtils = new ZipUtils();
            zipUtils.downloadFolder(yqZtcgFiles, zipName, response, uplodPath);
            //   ZipUtils.downloadZip(response, zipName, pocZipFile);
        }
    }

    /**
     * 修改发布状态
     *
     * @param chengguoIds 需要删除的专题成果主键
     * @return 结果
     */
    @Override
    public int updateIssueState(String[] chengguoIds, String state) {
        String tableCode = SecurityUtils.getTenantCode();
        String cgTbale = tableCode + Constants.TABLE_YQ_ZHUANTI_CHENGUO;
        List<YqZhuantiChengguo> yqZhuantiChengguos = yqZhuantiChengguoMapper.selectYqZhuantiChengguoByChengguoIdS(chengguoIds, cgTbale);
        String userId=String.valueOf(SecurityUtils.getUserId());
        boolean allMatch = yqZhuantiChengguos.stream().allMatch(a -> userId.equals(a.getCreatorId()));
        if (!allMatch) {
            throw new ServiceException("您选择的数据中包含其他人发布的数据,请重新选择!");
        }
        return yqZhuantiChengguoMapper.updateIssueState(chengguoIds, cgTbale, state);
    }

    /**
     * 上传封面
     *
     * @param file
     * @return
     */
    @Override
    public R<YqZtcgFile> uploadFile(MultipartFile file, String id) {
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        String tableCode = SecurityUtils.getTenantCode();

        if (StringUtils.isBlank(id)) {
            id = String.valueOf(SnowflakeIdGenerator.generateId());
        }
        try {
            // 上传并返回访问地址
            String url = PictureUploadUtils.upload(uplodPath, file);
            YqZtcgFile yqZtcgFile = new YqZtcgFile();
            yqZtcgFile.setFileName(FileUtils.getName(url));
            yqZtcgFile.setFilePath(url);
            yqZtcgFile.setFileSize(PictureUploadUtils.bytesTrans(file.getSize()));
            yqZtcgFile.setFileId(String.valueOf(SnowflakeIdGenerator.generateId()));
            yqZtcgFile.setChengguoId(id);
            String fileTable = tableCode + Constants.TABLE_YQ_ZTCG_FILE;
            ztcgFileMapper.insertYqZtcgFilee(yqZtcgFile, fileTable);
            return R.ok(yqZtcgFile);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean fileDelete(String id) {
        String fileTable = SecurityUtils.getTenantCode() + Constants.TABLE_YQ_ZTCG_FILE;
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        YqZtcgFile yqZtcgFiles = ztcgFileMapper.selectYqZtcgFileById(id, fileTable);
        File file = new File(uplodPath + yqZtcgFiles.getFilePath());
        int suffix = yqZtcgFiles.getFilePath().lastIndexOf(".");
        if (suffix < 0) {
            return false;
        }
        if (file.exists()) {
            //如果文件存在就删除文件
            file.delete();
            ztcgFileMapper.deleteYqZtcgFileById(id, fileTable);
            return true;
        }
        return false;
    }

}
